/*
 * @# SessionInterceptor.java 2011-5-23 下午06:19:35
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.sen.pro.switches.core.interceptor;

import java.util.Map;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.sen.common.util.net.Encoder;

/**
 * 判断用户是否已登陆.
 * 
 * @author tian qingsen
 */
public final class SessionInterceptor extends BaseInterceptor {

	private static final long serialVersionUID = 4213745163539945816L;
	private static Logger LOG = Logger.getLogger(SessionInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Map<String, Object> sessionMap = ActionContext.getContext().getSession();
		String sessionUserName = SessionFetcher.from(sessionMap).getUserName();

		// 跳转处理
		if (sessionUserName != null || isIgnoredSession(invocation.getInvocationContext().getName())) {
			return invocation.invoke();
		}

		String sessionOutMessage = "您还没有登录或登陆超时，请重新登陆！";
		if (LOG.isInfoEnabled()) {
			LOG.info(sessionOutMessage);
		}

		// ajax处理
		if (isAjaxRequest()) {
			setErrorTipMessage(TIMEOUT_TYPE, Encoder.encode(sessionOutMessage));
			return "none";
		}

		ActionContext.getContext().put("sessionOutMessage", sessionOutMessage);
		return "timeout";
	}

	private boolean isIgnoredSession(String actionName) {
		return "login".equals(actionName) || "logout".equals(actionName);
	}

}
